package LogTool

import (
	"fmt"
	"gitee.com/dadjin/my-commonly-used-go-func/MyTool/FileTool"
	"math/rand"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

//输出exe的相对路径
//相当于./logDir/Ymd.log
func LogPutDir(logDir string, info string) {
	now := time.Now()
	exePath, err := os.Executable()
	if err != nil {
		fmt.Println("Failed to get exe directory:" + err.Error())
	}
	AbsolutePath := filepath.Dir(exePath) + logDir + "/" + now.Format("20060102") + ".log"
	FileTool.MkFileNotDir(AbsolutePath)
	FileTool.AppendToFile(AbsolutePath, "["+now.Format("2006-01-02 15:04:05")+"] "+info+"\n")
}

func LogPutDirHasLimitMB(logDir string, info string, sizeLimitMB int) {
	now := time.Now()
	exePath, err := os.Executable()
	if err != nil {
		fmt.Println("Failed to get exe directory:" + err.Error())
	}
	AbsolutePath := filepath.Dir(exePath) + logDir + "/" + now.Format("20060102") + ".log"
	FileTool.MkFileNotDir(AbsolutePath)
	FileTool.AppendToFile(AbsolutePath, "["+now.Format("2006-01-02 15:04:05")+"] "+info+"\n")
	RenamingFilesBeyondLogLimitSizeMB(AbsolutePath, sizeLimitMB)
}

//输出exe的相对路径
//相当于./logFile.log
func LogPutFile(logFile string, info string) {
	now := time.Now()
	exePath, err := os.Executable()
	if err != nil {
		fmt.Println("Failed to get exe directory:" + err.Error())
	}
	AbsolutePath := filepath.Dir(exePath) + logFile + ".log"
	FileTool.MkFileNotDir(AbsolutePath)
	FileTool.AppendToFile(AbsolutePath, "["+now.Format("2006-01-02 15:04:05")+"] "+info+"\n")
}

//删除某文件夹的过期日志操作
func deleteOldFiles(folderPath string, days int) {
	now := time.Now()
	cutoff := now.AddDate(0, 0, -days)

	err := filepath.Walk(folderPath, func(path string, info os.FileInfo, err error) error {
		if filepath.Ext(path) != ".log" {
			return nil
		}
		if err != nil {
			return err
		}

		if !info.IsDir() && info.ModTime().Before(cutoff) {
			err = os.Remove(path)
			if err != nil {
				fmt.Println("无法删除过期日志文件:"+path, false)
			} else {
				fmt.Println("已删除过期日志文件:"+path, false)
			}
		}

		return nil
	})

	if err != nil {
		fmt.Println("遍历文件夹时出错："+err.Error(), false)
	}
}

/*
filePath 文件路径
sizeLimitMB 大小限制(MB)
*/
func RenamingFilesBeyondLogLimitSizeMB(filePath string, sizeLimitMB int) {
	if sizeLimitMB < 1 {
		return
	}

	fileInfo, err := os.Stat(filePath)
	if err != nil {
		fmt.Println("Failed to obtain log file("+filePath+") information:"+err.Error(), false)
		return
	}
	fileSize := fileInfo.Size()
	sizeLimitB := int64(sizeLimitMB * 1024 * 1024)

	if fileSize > sizeLimitB {
		now := time.Now()
		//时分秒毫秒+5位随机数
		renameSuffix := "_" + strings.ReplaceAll(now.Format("150405.000"), ".", "") + strconv.Itoa(rand.Intn(90000)+10000) + ".log"
		newFilePath := filePath + renameSuffix
		err := os.Rename(filePath, newFilePath)
		if err != nil {
			fmt.Println("Renaming log file("+filePath+") failed:"+err.Error(), false)
			return
		}
		fmt.Println("File "+filePath+" has been renamed to "+newFilePath, false)
	}
}
